package flc.ast.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseEditVideoFragment;
import flc.ast.R;
import flc.ast.activity.VideoEditActivity;
import flc.ast.adapter.VideoMusicAdapter;
import flc.ast.bean.MusicBean;
import flc.ast.databinding.FragmentVideoMusicBinding;
import flc.ast.utils.Content;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.FileUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link VideoMusicFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class VideoMusicFragment extends BaseEditVideoFragment<FragmentVideoMusicBinding> {

    public static final int INDEX = Content.INDEX_MUSIC;
    private List<MusicBean> mMusicBeanList;
    private VideoMusicAdapter mMusicAdapter;
    private int tmpPos;
    private String mMusicPath;
    private boolean mClickClose = true;
    private float voiceCount = 0.0f;

    public static VideoMusicFragment newInstance() {
        VideoMusicFragment fragment = new VideoMusicFragment();
        return fragment;
    }

    @Override
    public void onShow() {
        if (mMusicAdapter != null) {
            mMusicAdapter.getItem(tmpPos).setSelected(false);
            tmpPos = 0;
            mMusicAdapter.notifyDataSetChanged();
        }
        mMusicPath = "";
        mVideoEditActivity.mode = VideoEditActivity.MODE_MUSIC;
    }

    @Override
    public void backToMain() {
        if (!TextUtils.isEmpty(mMusicPath) && !mMusicPath.equals(mVideoEditActivity.getMainPath())) {
            mMusicPath = "";
        }
//        mVideoEditActivity.mVideoView.setVideoPath(mVideoEditActivity.getMainPath());
        mVideoEditActivity.mVideoView.setVideoPath(mVideoEditActivity.getMainPath());
        mVideoEditActivity.mVideoView.seekTo(1);
        mVideoEditActivity.mVideoView.start();
        mVideoEditActivity.mImageView.setImageResource(R.drawable.azant);
        mVideoEditActivity.mode = VideoEditActivity.MODE_NONE;
        mVideoEditActivity.showFunc();
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_video_music;
    }

    @Override
    protected void initView() {
        mMusicBeanList = new ArrayList<>();
        mMusicPath = "";
        tmpPos = 0;

        mDataBinding.rvVideoMusic.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mMusicAdapter = new VideoMusicAdapter();
        mDataBinding.rvVideoMusic.setAdapter(mMusicAdapter);
        mMusicAdapter.setOnItemClickListener(this);
        mDataBinding.llClose.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (!FastClickUtil.isFastClick()) {
            switch (view.getId()) {
                case R.id.llClose:
                    if (mClickClose) {
                        mClickClose = false;
                        mDataBinding.ivClose.setSelected(true);
                    } else {
                        mClickClose = true;
                        mDataBinding.ivClose.setSelected(false);
                    }
                    break;
                default:
                    super.onClick(view);
                    break;
            }
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mMusicAdapter.getItem(tmpPos).setSelected(false);
        mMusicAdapter.getItem(position).setSelected(true);
        tmpPos = position;
        mMusicAdapter.notifyDataSetChanged();

        if (mVideoEditActivity.mVideoView.isPlaying()) {
            mVideoEditActivity.mVideoView.pause();
            mVideoEditActivity.mImageView.setImageResource(R.drawable.abof);
        }
        showDialog(getString(R.string.video_music_loading) + 0 + "%");
        String musicPath = saveToSDCard(mMusicAdapter.getItem(position).getMusicUrl());  // 将raw文件下的音乐下载到本地指定目录
        mMusicPath = FileUtil.generateFilePath(Content.app_tmp_video, ".mp4");
        //参数分别是视频路径，音频路径，输出路径,原始视频音量(1为100%,0.7为70%,以此类推),添加音频音量
        if (mClickClose) {
            voiceCount = 1.0f;
        } else {
            voiceCount = 0.0f;
        }
        EpEditor.music(mVideoEditActivity.getMainPath(), musicPath, mMusicPath, voiceCount, 1.5f, new OnEditorListener() {
            @Override
            public void onSuccess() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        FileUtils.delete(musicPath);  // 将下载的音乐文件删掉，防止下载了太多的音乐文件
                        mVideoEditActivity.mPlayVideo = mMusicPath;
                        mVideoEditActivity.mVideoView.setVideoPath(mMusicPath);
                        mVideoEditActivity.mVideoView.seekTo(1);
                        mVideoEditActivity.mVideoView.start();
                        mVideoEditActivity.mImageView.setImageResource(R.drawable.azant);
                    }
                });
            }

            @Override
            public void onFailure() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        ToastUtils.showShort(R.string.video_music_fail);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                showDialog(getString(R.string.video_music_loading) + Math.round(progress * 100) + "%");
            }
        });
    }

    @Override
    protected void initData() {
        getMusicData();

        onShow();
    }

    private String saveToSDCard(int music) {
        try {
            InputStream inStream = getResources().openRawResource(music);
            String path = FileUtil.generateFilePath(Content.app_tmp_video, ".mp4");
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            byte[] buffer = new byte[10];
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] bs = outStream.toByteArray();
            fileOutputStream.write(bs);
            outStream.close();
            inStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void applyMusicVideo() {
        if (!TextUtils.isEmpty(mMusicPath) && !mMusicPath.equals(mVideoEditActivity.getMainPath())) {
            mVideoEditActivity.changeMainPath(mMusicPath, true);
            ToastUtils.showShort(R.string.video_music_success);
        }
        backToMain();
    }

    private void getMusicData() {
        String[] name = getResources().getStringArray(R.array.music_name);
        mMusicBeanList.add(new MusicBean(R.raw.music1, name[0], R.drawable.ayy1, false));
        mMusicBeanList.add(new MusicBean(R.raw.music2, name[1], R.drawable.ayy2, false));
        mMusicBeanList.add(new MusicBean(R.raw.music3, name[2], R.drawable.ayy3, false));
        mMusicBeanList.add(new MusicBean(R.raw.music4, name[3], R.drawable.ayy4, false));
        mMusicBeanList.add(new MusicBean(R.raw.music5, name[4], R.drawable.ayy5, false));
        mMusicAdapter.setList(mMusicBeanList);
    }

}